<template>
    <div class="score-rules">
        <div class="top">
            <a-form layout="inline" :form="form1" @submit="onSearchSubmit">
                <a-form-item label="角色名称">
                    <a-input placeholder="请输入角色名称"
                        v-decorator="['searchName',
                            { rules: [
                                { required: true, message: '请输入角色名称' },
                            ] }
                        ]"
                    ></a-input>
                </a-form-item>
                <a-form-item>
                    <a-button type="primary" html-type="submit" :loading="loading">搜索</a-button>
                    <a-button type="danger" style="margin-left: 15px;" @click="onReset" :loading="loading">重置</a-button>
                </a-form-item>
            </a-form>
            <a-button type="primary" class="btn-add" @click="onAdd">新增</a-button>
        </div>
        <a-table :columns="columns" :data-source="list" rowKey="id"
            bordered
            :loading="loading"
            :pagination="pagination"
            @change="onPageChange"
        >
            <span slot="ruleType"  slot-scope="text">{{getRuleType(text)}}</span>
            <span slot="scoringRules"  slot-scope="text">{{getScoringType(text)}}</span>
            <span slot="ratingDescription"  slot-scope="text">{{text || '-'}}</span>
            <span slot="action" slot-scope="text, record">
                <span class="action-btn" @click="onEdit(record)">修改</span>
                <span class="action-btn" @click="onDetele(record.id)">删除</span>
            </span>
        </a-table>
        <a-modal :visible="visible" :footer="null"
            :title="type==='add'?'新增系数分配':'修改系数分配'"
            @cancel="onCancel"
        >
            <a-form :form="form" @submit="onSubmit">
                <a-form-item label="打分类别"
                    :label-col="formItemLayout.labelCol"
                    :wrapper-col="formItemLayout.wrapperCol"
                >
                    <a-select placeholder="请选择打分类别"
                        @change="onChangeRuleType"
                        v-decorator="['ruleType',
                            { rules: [
                                { required: true, message: '请选择打分类别' },
                            ] }
                        ]"
                    >
                        <a-select-option v-for="(item, index) in ruleTypeList" :key="index"
                            :value="item.value"
                        >{{item.label}}</a-select-option>
                    </a-select>
                </a-form-item>
                <a-form-item label="角色"
                    :label-col="formItemLayout.labelCol"
                    :wrapper-col="formItemLayout.wrapperCol"
                    v-show="ruleType"
                >
                    <a-select placeholder="请选择角色"
                        v-decorator="['roleName',
                            { rules: [
                                { required: true, message: '请选择角色' },
                            ] }
                        ]"
                    >
                        <a-select-option v-for="(item, index) in roleList" :key="index"
                            :value="item.id"
                        >{{item.name}}</a-select-option>
                    </a-select>
                </a-form-item>
                <a-form-item label="打分类型"
                    :label-col="formItemLayout.labelCol"
                    :wrapper-col="formItemLayout.wrapperCol"
                >
                    <a-select placeholder="请选择打分类型"
                        v-decorator="['scoringRules',
                            { rules: [
                                { required: true, message: '请选择打分类型' },
                            ] }
                        ]"
                    >
                        <a-select-option v-for="(item, index) in scoringRulesType" :key="index"
                            :value="item.value"
                        >{{item.label}}</a-select-option>
                    </a-select>
                </a-form-item>
                <a-form-item label="打分系数"
                    :label-col="formItemLayout.labelCol"
                    :wrapper-col="formItemLayout.wrapperCol"
                >
                    <a-input-number :min="1" :max="100"  placeholder="系数"
                        v-decorator="['percentage',
                            { rules: [
                                { required: true, message: '请填写打分系数' },
                            ] }
                        ]"
                    />
                </a-form-item>
                <a-form-item :wrapper-col="{offset: 6}">
                    <a-button type="primary" html-type="submit" :loading="addLoading">提交</a-button>
                </a-form-item>
            </a-form>
        </a-modal>
        <a-modal :visible="addVisible" title="新增系数分配" :width="800"
            :footer="null"
            @cancel="onAddCancel"
        >
            <a-form>
                <a-form-item label="打分类别"
                    :label-col="formItemLayout.labelCol"
                    :wrapper-col="formItemLayout.wrapperCol"
                >
                    <a-select placeholder="请选择打分类别"
                        @change="onChangeRuleType"
                        style="width: 300px;"
                        :value="ruleType"
                    >
                        <a-select-option v-for="(item, index) in ruleTypeList" :key="index"
                            :value="item.value"
                        >{{item.label}}</a-select-option>
                    </a-select>
                </a-form-item>
                <a-form-item label="角色"
                    :label-col="formItemLayout.labelCol"
                    :wrapper-col="formItemLayout.wrapperCol"
                    v-show="ruleType"
                >
                    <a-select placeholder="请选择角色"
                        style="width: 300px;"
                        @change="onRoleChange"
                        :value="addRoleType||'请选择'"
                    >
                        <a-select-option v-for="(item, index) in roleList" :key="index"
                            :value="item.id"
                        >{{item.name}}</a-select-option>
                    </a-select>
                </a-form-item>
                <a-form-item label="打分类型"
                    :label-col="formItemLayout.labelCol"
                    :wrapper-col="formItemLayout.wrapperCol"
                >
                    <a-select placeholder="请选择打分类型"
                        style="width: 300px;"
                        :value="addRuleType||'请选择'"
                        @change="onAddRuleTypeChange"
                    >
                        <a-select-option v-for="(item, index) in scoringRulesType" :key="index"
                            :value="item.value"
                        >{{item.label}}</a-select-option>
                    </a-select>
                </a-form-item>
                <a-form-item label="评分类别"
                    :label-col="formItemLayout.labelCol"
                    :wrapper-col="formItemLayout.wrapperCol"
                    v-for="(item, index) in addList" :key="index"
                >
                    <div style="position: relative;">
                        <a-select placeholder="请选择评分类别"
                            style="width: 200px"
                            :value="item.scoredTypeId || '请选择'"
                            @change="val => onAddScoredTypeChange(val, index)"
                        >
                            <a-select-option v-for="(item, index) in scoreTypeList" :key="index"
                                :value="item.id"
                            >{{item.ratingDescription}}</a-select-option>
                        </a-select>
                        <span style="margin-left: 30px">得分系数：</span> 
                        <a-input-number :min="1" :max="100"  placeholder="系数"
                            :value="item.percentage"
                            @change="val => onAddPercentageChange(val, index)"
                        />
                        <div class="delete" v-show="index !== 0"
                            style="position: absolute; right: 80px; top: 0;"
                        >
                            <a-icon type="delete" class="icon" @click="onDeleteOnline(index)"
                                style="font-size: 16px;color:red;"
                            />
                        </div>
                    </div>
                </a-form-item>
                <a-form-item :wrapper-col="{offset: 6}">
                    <a-button type="primary" html-type="submit" :loading="addLoading" @click="onAddSubmit">提交</a-button>
                    <a-button type="primary" style="margin-left: 15px;" @click="onAddOnline" v-show="addList.length <4">新增行</a-button>
                </a-form-item>
            </a-form>
        </a-modal>
    </div>
</template>

<script>
import { getKpiRules, getRoles, addKpiRules, updateKpiRule, deleteKpiRule, getScoredTypeById } from '@/services';

const columns = [
    { title: '打分类别', dataIndex: 'ruleType', scopedSlots: { customRender: 'ruleType' }},
    { title: '打分类型', dataIndex: 'scoringRules', scopedSlots: { customRender: 'scoringRules' } },
    { title: '角色', dataIndex: 'roleName' },
    { title: '评分类别', dataIndex: 'ratingDescription', scopedSlots: { customRender: 'ratingDescription' }  },
    { title: '打分系数', dataIndex: 'percentage' },
    { title: '操作', key: 'action', align: 'center', scopedSlots: { customRender: 'action' } },
]

const ruleTypeList = [
    { value: 0, label: '部门' },
    { value: 1, label: '个人' },
]

const scoringRulesType = [
    { value: 'superiorScore', label: '上级打分' },
    { value: 'subordinateScore', label: '下属打分' },
    { value: 'peersScore', label: '同级打分' },
    { value: 'selfScore', label: '自我打分' },
]

export default {
    name: 'ScoreRules',
    data(){
        return {
            scoringRulesType,
            ruleTypeList,
            addVisible: false,
            visible: false,
            addLoading: false,
            type: 'add',
            formItemLayout: {
                labelCol: { span: 6 },
                wrapperCol: { span: 16 },
            },
            form1: this.$form.createForm(this),
            form: this.$form.createForm(this),
            columns,
            loading: false,
            list: [],
            pagination: {},
            roleList: [],
            editId: '',
            ruleType: 1,
            addList: [{
                key: 1,
                scoredTypeId: '',
                percentage: ''
            }],
            scoreTypeList: [],
            addRoleType: '',
            addRuleType: '',
            searchName: ''
        }
    },
    mounted(){
        this.getRulesList();
        this.getAllRoles();
    },
    methods: {
        // 切换打分类型
        onChangeRuleType(type){
            if(type === 0){
                this.getRoleTypeById(0)
                
            }
            this.addList= [{
                key: 1,
                scoredTypeId: '',
                percentage: ''
            }]
            this.addRoleType = ''
            this.ruleType = type;
        },
        // 新增按钮
        onAdd(){
            // this.visible = true;
            this.addVisible = true;
            this.type = "add"
        },
        // 通过部门或用户id获取评分类别
        async getRoleTypeById(id){
            let res = await getScoredTypeById(id);
            if(res.responseObject){
                this.scoreTypeList = res.responseObject;
            }
        },
        // 关闭modal
        onCancel(){
            this.visible = false;
            this.form.resetFields();
        },
        // 删除按钮
        onDetele(id){
            const _that = this;
            this.$confirm({
                title: `确认删除这条 系数分配 吗? `,
                okText: "删除",
                okType: 'danger',
                cancelText: "取消",
                onOk(){
                    _that.deleteKpiRule(id)
                }
            })
        },
        // 切换分页
        onPageChange(pagination, filters, sorter){
            let { current, pageSize } = pagination;
            this.getRulesList(current);
        },
        // 获取打分规则列表
        async getRulesList(page=1){
            const { searchName } = this;
            this.loading = true;
            let res = await getKpiRules({ page, searchName });
            this.loading = false;
            if(res.responseObject){
                let { count, data } = res.responseObject;
                this.list = data;
                let pagination = { ...this.pagination };
                pagination.total = count;
                pagination.current = page;
                pagination.pageSize = 10;
                pagination.showTotal = (total, range) => `共找到 ${total} 条数据`
                this.pagination = pagination;
            }
        },
        // 获取所有职务列表
        async getAllRoles(){
            let res = await getRoles({ pageSize: 99 });
            if(res.responseObject) {
                this.roleList = res.responseObject.Result
            }
        },
        // 修改按钮
        onEdit(params){
            this.ruleType = params.ruleType ? 1 : 0;
            this.form.getFieldDecorator('ruleType');
            this.form.getFieldDecorator('scoringRules');
            this.form.getFieldDecorator('percentage');
            this.form.getFieldDecorator('roleName');
            this.type = 'edit';
            this.visible = true;
            this.editId = params.id;
            this.form.setFieldsValue({
                ruleType: params.ruleType === 0 ? 0 : 1,
                scoringRules: params.scoringRules,
                percentage: params.percentage,
                roleName: params.ruleType === 0 ? '请选择角色' : params.ruleType
            })
        },
        // 打分类别
        getRuleType(type){
            if(type === 0) return '部门';
            else return '个人';
        },
        // 打分类型
        getScoringType(type){
            if(type === 'superiorScore') return '上级打分';
            else if(type === 'subordinateScore') return '下属打分';
            else if(type === 'peersScore') return '同级打分';
            else if(type === 'selfScore') return '自我打分';
        },
        // 提交按钮
        onSubmit(e){
            e.preventDefault();
            const _that = this;
            const { type, editId } = this;
            this.form.validateFields((err, values) => {
                if (!err) {
                    let { ruleType, roleName, percentage, scoringRules } = values;
                    if(ruleType && roleName === '请选择角色') {
                        _that.$message.error('请先选择角色', 1);
                        return;
                    }
                    let item = _that.roleList.filter(item => item.id === roleName);
                    let data = {
                        percentage,
                        scoringRules,
                        ruleType: ruleType === 1 ? roleName : 0,
                        roleName: item[0] && ruleType === 1 ? item[0].name : '无'
                    };
                    // 新增
                    if(type === 'add') _that.onAddRules(data);
                    if(type === 'edit') {
                        _that.updateRule(Object.assign(data, { id: editId }))
                    }
                }
            })
        },
        // 新增打分规则
        async onAddRules(params){
            this.addLoading = true;
            let res = await addKpiRules(params);
            this.addLoading = false;
            const _that = this;
            if(res.success) {
                this.$message.success('新增规则成功', 1, ()=>{
                    // _that.onCancel();
                    _that.onAddCancel();
                    _that.getRulesList(_that.pagination.current);
                })
            }else if(!res.success && res.errorMessage){
                this.$message.error(res.errorMessage, 1)
            }
        },
        // 修改打分规则
        async updateRule(params){
            this.addLoading = true;
            let res = await updateKpiRule(params);
            this.addLoading = false;
            const _that = this;
            if(res.success) {
                this.$message.success('修改规则成功', 1, ()=>{
                    _that.onCancel();
                    _that.getRulesList(_that.pagination.current);
                })
            }else if(!res.success && res.errorMessage){
                this.$message.error(res.errorMessage, 1)
            }
        },
        // 删除规则
        async deleteKpiRule(id){
            this.loading = true;
            let res = await deleteKpiRule(id);
            const _that = this;
            if(res.success){
                this.$message.success('删除规则成功', 1, ()=>{
                    _that.getRulesList(_that.pagination.count > 11 ? _that.pagination.current : 1);
                })
            }else if(res.errorMessage){
                this.loading = false;
                this.$message.error(res.errorMessage, 1)
            }
        },
        // 新增时切换角色
        onRoleChange(val){
            this.addRoleType = val;
            this.getRoleTypeById(val);
        },
        // 关闭新增modal
        onAddCancel(){
            this.addVisible = false;
            this.addRoleType = '';
            this.addRuleType = '';
            this.addList = [{
                key: 1,
                scoredTypeId: '',
                percentage: ''
            }]
        },
        onAddOnline(){
            this.addList.push({
                scoredTypeId: '',
                percentage: ''
            })
        },
        // 删除一行
        onDeleteOnline(index){
            this.addList.splice(index, 1)
        },
        // 新增得分系数改变
        onAddPercentageChange(val, index){
            let addList =  this.addList;
            addList[index].percentage = val;
            this.addList = addList;
        },
        // 新增评分类别改变
        onAddScoredTypeChange(val, index){
            let addList =  this.addList;
            addList[index].scoredTypeId = val;
            this.addList = addList;
        },
        // 新增打分类型改变
        onAddRuleTypeChange(val){
            this.addRuleType = val;
        },
        // 新增提交按钮
        onAddSubmit(){
            let { addList, addRuleType, addRoleType, ruleType, roleList, scoreTypeList } = this;
            if(!addRuleType){
                this.$message.error('请先打分类型', 1);
                return;
            }
            if(ruleType === 1 && !addRoleType){
                this.$message.error('请先选择角色', 1);
                return;
            }
            if(!this.jyArr(addList)){
                this.$message.error('请先检查表单', 1);
                return;
            }
            let item = roleList.filter(item => item.id === addRoleType);
            let data = [];
            addList.map(_item=>{
                let item1 = scoreTypeList.filter(item => item.id === _item.scoredTypeId);
                data.push({
                    ruleType: addRoleType,
                    roleName: item[0] ? item[0].name : '无',
                    percentage: _item.percentage,
                    scoringRules: addRuleType,
                    scoredTypeId: _item.scoredTypeId,
                    ratingDescription: item1[0].ratingDescription
                })
            })
            console.log( JSON.stringify(data));
            this.onAddRules(data);
            // console.log(data);
        },
        jyArr(arr){
            let str = true;
            arr.map(item=>{
                for(let k in item){
                    if(!item[k]){
                        str = false
                    }
                }
            })
            return str;
        },
        // 点击搜索按钮
        onSearchSubmit(e){
            e.preventDefault();
            const _that = this;
            this.form1.validateFields((err, values) => {
                if (!err) {
                    const { searchName } = values;
                    _that.searchName = searchName;
                    _that.getRulesList()
                }
            })
        },
        // 重置按钮
        onReset(){
            this.searchName = "";
            this.form1.resetFields();
            this.getRulesList();
        }
    }
}
</script>
<style lang="less" scoped>
@import '../global.less';
    .score-rules{
        padding: 20px;
        .top{
            height: 60px;
            overflow: hidden;
            margin-bottom: 5px;
            display: flex;
            justify-content: space-between;
        }
        .action-btn{
            color: @primary;
            margin: 0 10px;
            cursor: pointer;
        }
        .item{
            position: relative;
            .delete{
                position: absolute;
                right: -40px;
            }
        }  
    }
</style>